import { useReducer } from 'react';
import { Form } from 'antd';

import type { ListTableType, ListTableActionType } from '../utils/types';

const listTableReducerTodo = (state: ListTableType, action: ListTableActionType) => {
  switch (action.type) {
    case 'init': {
      const { listConfigData } = action;
      return {
        ...state,
        addFlag:
          listConfigData.baseConfig?.allowInsertDelete &&
          listConfigData.columnList?.filter((item: any) => item.isEditable).length !== 0,
        editedCol: '',
        ...action,
      };
    }
    case 'setAddFlag':
      return {
        ...state,
        addFlag: action.addFlag,
      };
    case 'setSelectedKey':
      return {
        ...state,
        selectedKey: action.selectedKey,
      };
    case 'setFilterIcon':
      return {
        ...state,
        filterIcon: action.filterIcon,
      };
    case 'setEditedCol':
      return {
        ...state,
        ...action,
      };
    // 根据key g更新标识数据
    case 'setKeyAndValue': {
      return {
        ...state,
        ...action,
      };
    }
    default:
      return state;
  }
};

const initStateData = {
  editedCol: '',
  screen: [],
  addFlag: false,
  tableLoading: true,
  filterIcon: false,
  selectedKey: [],
  tableParameters: { page: 1 },
  isFirst: true, // 首次加载
};

const UseListTableHook = () => {
  const [state, dispatch] = useReducer(listTableReducerTodo, initStateData);
  // table区域form
  const [tableForm] = Form.useForm();

  return {
    state,
    dispatch,
    tableForm,
  };
};

export default UseListTableHook;
